package com.irssproject.app.dao.main.impl;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.irssproject.app.dao.main.iface.UsersDAO;
import com.irssproject.app.entitats.User;
import com.irssproject.app.utils.Constants;

public class UsersDAOHibernate extends HibernateDaoSupport implements UsersDAO {

    public User autenticarUsuari(User usuari) throws Exception {
        try {
            User us = (User) getHibernateTemplate().find("from User where login = ? and password = ?", new Object[]{usuari.getLogin(), usuari.getPassword()}).get(0);
            return us;
        } catch (DataAccessException e) {
            throw new Exception(Constants.EXCEPTION_LOGIN_INCORRECT);
        }
    }

    public void deleteUsuari(User usuari) {
        getHibernateTemplate().delete(usuari);
    }

    public User getUsuari(String login) {
        try {
            return (User) getHibernateTemplate().find("from User where login = ?", login).get(0);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    }

    public Boolean insertUsuari(User usuari) throws Exception {
        Boolean insertOK = Boolean.TRUE;
    	try {
            getHibernateTemplate().save(usuari);
        
        } catch (DataAccessException e) {
        	insertOK = Boolean.TRUE;
        }
        return insertOK;
    }

    public void updateUsuari(User usuari) throws Exception {
        User user = (User) getHibernateTemplate().get(User.class, usuari.getId());

        if (!usuari.getPassword().isEmpty()) {
       		user.setPassword(usuari.getPassword());
    	}
        user.setName(usuari.getName());
        user.setEmail(usuari.getEmail());
        user.setPlace(usuari.getPlace());

        getHibernateTemplate().update(user);
    }

    @SuppressWarnings("unchecked")
	public List<User> getListUsuaris() {
        return (List<User>)getHibernateTemplate().find("From User");
    }
    @Override
    public boolean existeixUsuari(String login, String password){
        User us = (User) getHibernateTemplate().find("from User where login = ? and password = ?", new Object[]{login, password}).get(0);

        if (us==null){
        	return false;
        }
        else return true;
    	
    }
}
